package com.tsd.aspect;

import com.tsd.core.annotation.DataFieldAuth;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.vo.HttpResult;
import com.tsd.system.entity.SysUserExt;
import com.tsd.system.utils.AuthViewFieldUtil;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @ClassName: CheckBindAspect
 * @Description: TODO
 * @Author: admin
 * @Date: 2022/11/14 11:30
 * @Version: 1.0
 */
@Order(1)
@Aspect
@Component
public class DataFieldAuthAspect {

    @Around(value = "@annotation(auth)")
    @SuppressWarnings("unchecked")
    public Object beforeCheckBind(ProceedingJoinPoint point, DataFieldAuth auth) throws Throwable {
        if (HlpUtils.isEmpty(auth.code())) {
            return point.proceed();
        }
        SysUserExt userExt = (SysUserExt) SecurityUtils.getSubject().getPrincipal();
        if (userExt == null) {
            throw new RuntimeException("请先登录");
        }
        Object returnData = point.proceed();
        if (returnData == null) {
            return null;
        }
        if (returnData instanceof HttpResult) {
            HttpResult<Object> result = (HttpResult<Object>) returnData;
            if (result.getData() == null) {
                return returnData;
            }
            if (result.getData() instanceof List) {
                List<Object> list = (List<Object>) result.getData();
                AuthViewFieldUtil.clearAuthViewField(auth.code(), list, userExt);
                result.setData(list);
            } else {
                Object object = result.getData();
                AuthViewFieldUtil.clearAuthViewField(auth.code(), object, userExt);
                result.setData(object);
            }
            return result;
        }
        return returnData;
    }
}
